package com.colorful.exceldemo.toolkit.excel;

import com.colorful.exceldemo.annotation.ExcelSelected;
import com.colorful.exceldemo.helper.SpringHelper;
import com.colorful.exceldemo.toolkit.EasyExcelUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 注解解析
 * @author kang junjie
 * @date 2022/6/2 15:04
 */
@Data
@Slf4j
@Component
public class ExcelSelectedResolve {
    /**
     * 下拉内容
     */
    private String[] source;

    /**
     * 设置下拉框的起始行，默认为第二行
     */
    private int firstRow;

    /**
     * 设置下拉框的结束行，默认为最后一行
     */
    private int lastRow;

    /**
     * 级联列
     */
    private int ref;

    /**
     * 通过对象存储级联键值对
     */
    private SourceMap sourceMap;

    public Map<String, List<String>> resolveSelectedSource(ExcelSelected excelSelected) {
        if (excelSelected == null) {
            return null;
        }
        // 获取固定下拉框的内容
        String[] source = excelSelected.source();
        if (source.length > 0) {
            return EasyExcelUtil.convertMap(source);
        }

        // 获取动态下拉框的内容
        Class<? extends ExcelDynamicSelect>[] classes = excelSelected.sourceClass();
        if (classes.length > 0 && ref == 0) {
            // 从容器中获取对象.方便注入其他内容
            ExcelDynamicSelect excelDynamicSelect = SpringHelper.getBean(classes[0]);
            Map<String, List<String>> dynamicSelectSource = excelDynamicSelect.getSource();
            if (dynamicSelectSource != null && dynamicSelectSource.size() > 0) {
                return dynamicSelectSource;
            }
        }
        // 有级联关系的列
        int ref = excelSelected.ref();
        if (ref != 0) {
            ExcelDynamicSelect excelDynamicSelect = SpringHelper.getBean(classes[0]);
            Map<String, List<String>> dynamicSelectSource = excelDynamicSelect.getSourceMap();
            if (dynamicSelectSource != null && dynamicSelectSource.size() > 0) {
                return dynamicSelectSource;
            }
        }
        return null;
    }
}
